var selectedId = null; // 选中的文章或视频ID
var resourceType = null;// 资源类型 (1:文章,2:视频,3:素材)
var currentTabName = ''; // 当前选中的Tab页名称
var userLookFlag = false; // Tab页(用户浏览)数据加载标识 false-还未加载过数据 true-已经加载过
var userShareFlag = false; // Tab页(用户分享)数据加载标识 (同上)
var userCopyFlag = false; // Tab页(用户换成我的)数据加载标识 (同上)


$(function () {
    // 绑定事件
    $('#tabs a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        let tabName = $(e.target).attr("aria-controls");
        toggleTab(tabName);
    })
})

/**
 * 根据ID获取文章或视频详情
 * @param id
 */
function loadArticleDetail(id, type) {
    console.log(id);
    // 1、参数校验
    if (id == null || type == null) {
        return;
    }
    selectedId = id;
    resourceType = type;
    // 2、清空数据
    removeDetailData();
    // 3、加载数据(根据当前选中的Tab名称)
    if (currentTabName == '') {
        currentTabName = "tab-userLook";
    }
    toggleTab(currentTabName);
    // 4、手动打开模态框
    $('#articleDetail').modal('show');
    if (resourceType == 1) {
        $("#myModalLabel").html("文章详情 (编号:" + selectedId + ")");
    } else if (resourceType == 2) {
        $("#myModalLabel").html("视频详情 (编号:" + selectedId + ")");
    }
    getArticleTabCount();
}

/**
 *
 */
function removeDetailData() {
    // 清空表格数据
    $("#jqGridUserLook").jqGrid("clearGridData");
    $("#jqGridUserShare").jqGrid("clearGridData");
    $("#jqGridUserCopy").jqGrid("clearGridData");

    // Flag全部为false，以防不加载数据
    userLookFlag = false;
    userShareFlag = false;
    userCopyFlag = false;
}

/**
 * 切换Tab
 * @param tabName Tab页名称
 */
function toggleTab(tabName) {
    //debugger
    if (currentTabName != tabName) {
        currentTabName = tabName;
    }
    console.log(tabName);
    // 切换Tab
    if (tabName == "tab-userLook") {
        if (!userLookFlag) {
            getUserLook();
            userLookFlag = true;
        }
        reloadUserLook();
    } else if (tabName == "tab-userShare") {
        if (!userShareFlag) {
            getUserShare();
            userShareFlag = true;
        }
        reloadUserShare();
    } else if (tabName == "tab-userCopy") {
        if (!userCopyFlag) {
            getUserCopy();
            userCopyFlag = true;
        }
        reloadUserCopy();
    }else {
        return;
    }
}

/**
 * 用户浏览详情
 */
function getUserLook() {
    $("#jqGridUserLook").jqGrid({
        url: baseURL + 'sys/articlelookdetaillog/userLookInfo',
        datatype: "json",
        colModel: [
            { label: '用户编号', name: 'userId', index: 'user_id',align: "center", width: 80},
            { label: '用户名称', name: 'userName', index: 'user_name',align: "center", width: 240},
            { label: '公众号', name: 'gzhName', index: 'gzh_name',align: "center", width: 110 },
            { label: '开始时间', name: 'lookTime', index: 'look_time',align: "center", width: 150 },
            { label: '结束时间', name: 'lookEndTime', index: 'look_end_time',align: "center", width: 150 },
            { label: '查看时长(单位:秒)', name: 'spentTime', index: 'spent_time',align: "center", width: 150 }
        ],
        viewrecords: true,
        height: 370,
        rowNum: 10,
        rowList : [10,20,50],
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPagerUserLook",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        postData:{'id': selectedId,'resourceType': resourceType},
        gridComplete:function(){
            $("#jqGridUserLook").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    })
}

/**
 * 用户浏览详情(刷新)
 */
function reloadUserLook() {
    $("#jqGridUserLook").jqGrid('setGridParam',{
        url: baseURL + 'sys/articlelookdetaillog/userLookInfo',
        postData:{'id': selectedId,'resourceType': resourceType},
        page:1
    }).trigger("reloadGrid");
}

/**
 * 用户分享详情
 */
function getUserShare() {
    $("#jqGridUserShare").jqGrid({
        url: baseURL + 'sys/barticleinfo/userShareInfo',
        datatype: "json",
        colModel: [
            { label: '用户编号', name: 'userId', index: 'user_id',align: "center", width: 80},
            { label: '用户名称', name: 'userName', index: 'userName',align: "center", width: 240},
            { label: '文章类别', name: 'articleCategory', index: 'articleCategory',align: "center", width: 180,
                formatter: function (value,options,rowData) {
                    if (value == 1) {
                        return "平台文章";
                    } else if (value == 2) {
                        return "早晚打卡文章";
                    } else {
                        return "";
                    }
                }
            },
            { label: '分享日期', name: 'createTime', index: 'createTime',align: "center", width: 160 }
        ],
        viewrecords: true,
        height: 370,
        rowNum: 10,
        rowList : [10,20,50],
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPagerUserShare",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        postData:{'id': selectedId,'resourceType': resourceType},
        beforeRequest: function() {
            if (resourceType == 2) {
                $("#jqGridUserShare").jqGrid("setLabel", "articleCategory","视频类别",'','');
            }
        },
        gridComplete:function(){
            $("#jqGridUserShare").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
}

/**
 * 用户分享详情(刷新)
 */
function reloadUserShare() {
    $("#jqGridUserShare").jqGrid('setGridParam',{
        url: baseURL + 'sys/barticleinfo/userShareInfo',
        postData:{'id': selectedId,'resourceType': resourceType},
        page:1
    }).trigger("reloadGrid");
}

/**
 * 用户换成我的详情
 */
function getUserCopy() {
    $("#jqGridUserCopy").jqGrid({
        url: baseURL + 'sys/barticleinfo/userCopyInfo',
        datatype: "json",
        colModel: [
            { label: '用户编号', name: 'userId', index: 'user_id',align: "center", width: 80},
            { label: '用户名称', name: 'userName', index: 'user_name',align: "center", width: 100},
            { label: '文章编号', name: 'id', index: 'id',align: "center", width: 80},
            { label: '文章名称', name: 'articleTitle', index: 'article_title',align: "center", width: 240 },
            { label: '创建日期', name: 'createTime', index: 'create_ime',align: "center", width: 160 }
        ],
        viewrecords: true,
        height: 370,
        rowNum: 10,
        rowList : [10,20,50],
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPagerUserCopy",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        postData:{'id': selectedId,'resourceType': resourceType},
        beforeRequest: function() {
            if (resourceType == 2) {
                $("#jqGridUserCopy").jqGrid("setLabel", "id","视频编号",'','');
                $("#jqGridUserCopy").jqGrid("setLabel", "articleTitle","视频名称",'','');
            }
        },
        gridComplete:function(){
            $("#jqGridUserCopy").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
}

/**
 * 用户换成我的详情(刷新)
 */
function reloadUserCopy() {
    $("#jqGridUserCopy").jqGrid('setGridParam',{
        url: baseURL + 'sys/barticleinfo/userCopyInfo',
        postData:{'id': selectedId,'resourceType': resourceType},
        page:1
    }).trigger("reloadGrid");
}

function getArticleTabCount() {
    // 获取文章 Tab 页，用户浏览数量
    $.ajax({
        type: "GET",
        url: baseURL + 'sys/articlelookdetaillog/getUserLookCountByArticleId',
        contentType: "application/json;charset=UTF-8",
        data: {'id': selectedId,'resourceType': resourceType},
        dataType: "JSON",
        success: function (r) {
            let tab = $("#tabs a[data-toggle='tab']")[0];
            $(tab).empty();
            if (r.code === 0) {
                $(tab).text("用户浏览("+r.userLookCount+")");
            } else {
                $(tab).text("用户浏览(0)");
            }
        }
    });
    // 获取文章 Tab 页，用户分享数量
    $.ajax({
        type: "GET",
        url: baseURL + 'sys/barticleinfo/getUserShareCountByArticleId',
        contentType: "application/json;charset=UTF-8",
        data: {'id': selectedId,'resourceType': resourceType},
        dataType: "JSON",
        success: function (r) {
            let tab = $("#tabs a[data-toggle='tab']")[1];
            $(tab).empty();
            if (r.code === 0) {
                $(tab).text("用户分享("+r.userShareCount+")");
            } else {
                $(tab).text("用户分享(0)");
            }
        }
    });
    // 获取文章 Tab 页，用户换成我的数量
    $.ajax({
        type: "GET",
        url: baseURL + 'sys/barticleinfo/getUserCopyCountByArticleId',
        contentType: "application/json;charset=UTF-8",
        data: {'id': selectedId,'resourceType': resourceType},
        dataType: "JSON",
        success: function (r) {
            let tab = $("#tabs a[data-toggle='tab']")[2];
            $(tab).empty();
            if (r.code === 0) {
                $(tab).text("用户换成我的("+r.userCopyCount+")");
            } else {
                $(tab).text("用户换成我的(0)");
            }
        }
    });
}